<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=yes"/>
	<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, minimal-ui" />
	<!--<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">-->
	<!--<meta content="yes" name="apple-mobile-web-app-capable">-->
	<!--<meta content="black" name="apple-mobile-web-app-status-bar-style">-->
	<!--<meta content="telephone=no" name="format-detection">-->
	<link rel="shortcut icon" type="image/x-icon" href="../static/favicon.ico">
	<link rel="bookmark" href="../static/favicon.ico"/>
	<title>MonsterCreator</title>
	<link rel="stylesheet" href="../static/css/common.css">
	<link rel="stylesheet" href="../static/css/draw_canvas.css">
	<script src="https://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/vconsole/3.0.0/vconsole.min.js"></script>
	<script src="../static/js/util.js"></script>
	<!--<script src="../script/jquery.min.js"></script>-->

</head>
<body ontouchmove="event.preventDefault()" ontouchend="event.preventDefault();">
<div id="wrap">
	<div id="mHead">
		<img src="../static/images/mHead.png" alt="">
	</div>
	<div id="topMenu">
		<div id="upload">
			<img src="../static/images/upload.gif" alt="上传">
		</div>
		<div id="save">
			<img src="../static/images/save.gif" alt="保存">
		</div>
		<div id="share">
			<img src="../static/images/share.gif" alt="分享">
		</div>
		<!--<div id="tip">-->
			<!--<img src="../static/images/info.gif" alt="">-->
		<!--</div>-->
		<div id="back">
			<img src="../static/images/usericon.gif" alt="返回">
		</div>
		<div id="clear">
			<img src="../static/images/clear.gif" alt="清除">
		</div>



	</div>
	<div id="head">
		<div class="headGrid1">
			<div id="largerCanvas">
				<img src="../static/images/plus.gif" alt="">
			</div>
			<div id="smallerCanvas">
				<img src="../static/images/dev.gif" style="transform: rotateY(180deg);" alt="">
			</div>
		</div>
		<div class="headGrid2">
			<div id="preView">
				<img src=""  alt="">
			</div>
		</div>
		<div class="headGrid3">
			<div id="pre">
				<img src="../static/images/unback.gif" alt="">
			</div>
			<div id="next">
				<img src="../static/images/unback.gif" style="transform: rotateY(180deg);" alt="">
			</div>
		</div>

	</div>
	<div id="main">
		<div id="canvasBox">
			<canvas id="canvas">
				您的瀏覽器不支持畫板!
			</canvas>
		</div>
	</div>

	<div id="allColor">

	</div>
	<div id="controlBoard">
		<div>
			<img src="../static/images/hand.gif" alt="" id="handMove">
		</div>
		<div class="bgc">
			<img src="../static/images/bg-white.gif" id="bgc">
		</div>
		<div class="nc">
			<span>
				<span id="trangle">
					<img src="../static/images/trangle.png" alt="">
				</span>
				<span id="c"></span>
				<span id="nowColor"></span>
			</span>
		</div>
		<div class="pen">
			<img src="../static/images/pen-active.gif" alt="" id="pencil">
		</div>
		<div>
			<img src="../static/images/eraser.gif" alt="" id="eraser">
		</div>
	</div>
	<canvas id="secondCanvas" style="display: none;"></canvas>
</div>

</body>
<script src="../static/js/common.js"></script>
<script>
    var allColorName = [
        'rgba(0,0,0,1)',
        'rgba(255,255,255,1)',
        'rgba(255,0,0,1)',
        'rgba(255,255,0,1)',
        'rgba(0,255,0,1)',
        'rgba(0,255,255,1)',
        'rgba(0,0,255,1)',
        'rgba(255,0,255,1)',
        'rgba(230,230,230,1)',
        'rgba(205,205,205,1)',

        'rgba(180,180,180,1)',
        'rgba(154,154,154,1)',
        'rgba(142,142,142,1)',
        'rgba(129,129,129,1)',
        'rgba(223,0,36,1)',
        'rgba(248,244,0,1)',
        'rgba(0,159,60,1)',
        'rgba(0,168,236,1)',
        'rgba(61,16,123,1)',
        'rgba(227,0,123,1)',

        'rgba(115,115,115,1)',
        'rgba(89,89,89,1)',
        'rgba(48,48,48,1)',
        'rgba(19,19,19,1)',
        'rgba(243,157,119,1)',
        'rgba(245,181,127,1)',
        'rgba(250,205,138,1)',
        'rgba(255,249,157,1)',
        'rgba(200,225,157,1)',
        'rgba(168,213,157,1)',

        'rgba(136,201,157,1)',
        'rgba(140,204,202,1)',
        'rgba(141,207,244,1)',
        'rgba(147,169,213,1)',
        'rgba(106,80,155,1)',
        'rgba(142,86,155,1)',
        'rgba(175,93,156,1)',
        'rgba(237,108,158,1)',
        'rgba(236,107,118,1)',
        'rgba(223,0,36,1)',

        'rgba(232,100,27,1)',
        'rgba(239,156,0,1)',
        'rgba(248,244,0,1)',
        'rgba(124,198,35,1)',
        'rgba(0,176,52,1)',
        'rgba(0,159,60,1)',
        'rgba(0,164,157,1)',
        'rgba(0,168,236,1)',
        'rgba(103,8,123,1)',
        'rgba(145,0,123,1)',

        'rgba(227,0,123,1)',
        'rgba(225,0,82,1)',
        'rgba(150,0,20,1)',
        'rgba(156,65,15,1)',
        'rgba(160,103,0,1)',
        'rgba(167,164,0,1)',
        'rgba(81,132,19,1)',
        'rgba(0,117,32,1)',
        'rgba(0,106,37,1)',
        'rgba(0,109,104,1)',

        'rgba(0,112,158,1)',
        'rgba(4,68,118,1)',
        'rgba(29,42,99,1)',
        'rgba(38,7,81,1)',
        'rgba(68,3,81,1)',
        'rgba(96,0,81,1)',
        'rgba(153,0,80,1)',
        'rgba(152,0,52,1)',
        'rgba(108,0,10,1)',
        'rgba(113,45,8,1)',

        'rgba(116,73,0,1)',
        'rgba(122,119,0,1)',
        'rgba(57,95,11,1)',
        'rgba(0,84,20,1)',
        'rgba(0,75,24,1)',
        'rgba(0,78,73,1)',
        'rgba(0,80,115,1)',
        'rgba(3,47,85,1)',
        'rgba(18,28,70,1)',
        'rgba(25,4,56,1)',

        'rgba(42,2,57,1)',
        'rgba(68,0,57,1)',
        'rgba(111,0,57,1)',
        'rgba(110,0,35,1)',
        'rgba(203,185,157,1)',
        'rgba(158,139,117,1)',
        'rgba(118,100,84,1)',
        'rgba(82,68,60,1)',
        'rgba(51,42,41,1)',
        'rgba(200,164,109,1)',

        'rgba(169,131,79,1)',
        'rgba(140,102,53,1)',
        'rgba(114,76,33,1)',
        'rgba(91,55,21,1)'
    ];//色板所有颜色
    var backgroundGroup = [
        {'bg_color' :'rgba(255, 255, 255, 1)', 'bg_image': '../static/images/bg-white.gif', 'bg_active_image': '../static/images/bg-white-1.gif'},
		{'bg_color': 'rgba(153, 153, 153, 1)', 'bg_image': '../static/images/bg-grey.gif', 'bg_active_image': '../static/images/bg-grey-1.gif'},
		{'bg_color': 'rgba(0, 255, 30, 1)', 'bg_image': '../static/images/bg-green.gif', 'bg_active_image': '../static/images/bg-green-1.gif'}
    ];//所有背景色列表
    var nowBgc = 0;//三个背景色，当前背景
    var nowColor, preColor;//nowColor 当前选中颜色，preColor 点击橡皮或手时暂时将当前颜色存在这里
    var backgroundColor = 'rgba(255,255,255,1)';//默认白色
	var monsterId = getQueryString("id") == null ? '' : getQueryString("id");

	console.log('monsterid:'+monsterId);

	var usr = JSON.parse(window.decodeURIComponent(getQueryString('usr')));

	var allmonster = JSON.parse(localStorage.getItem("monsters"));

	console.log(allmonster)

	if(usr != null){
		console.log(usr.name);
	}

    nowColor = 'rgba(0,0,0,1)';//默认黑色
    preColor = nowColor;//preColor初始为nowColor
    var largerMultiple = 2;//画板放大参数，2~6，默认2

    var historyCount = 20;//画图历史最多保存20步
    var defaultCanvas = [];//什么都没画时的状态 用于判断控制 是否可以上传保存等
    var blockList = [];//当前画板中的绘图信息存放数组
    var history = [];//绘图历史数组，用于存放绘图历史
    var nowStatus, allStatus;//用于绘图中前进后退的状态控制，当前状态和所有状态
    var bottomBtnUnactiveImg = [
        '../static/images/hand.gif',
        '../static/images/bg-white.gif',
        '',
        '../static/images/pen.gif',
        '../static/images/eraser.gif'
    ];//底部按钮未点击时的图片
	var preCanvasWidth, preCanvasHeight;
    var canvasWidth;//getView中计算出的画板宽高，是32的倍数
    var clientH;//在getView函数中获取的视窗高度
    var clientW;//在getView函数中获取的视窗宽度

    var eachWidth;//画板中每一个小方块的宽，eachWidth*32等于画板宽和高，通过屏幕宽高算出eachWidth，保证画板宽高值为32的倍数，解决画板小方块间空隙问题
    var normalWidth;//画板放大或缩小，normalWidth不变，变的是eachWidth;
    var paddingLeft;//画板左边距，用于获得画板中正确的x位置,
    var paddingTop;//画板上边距，用于获得画板中正确的y位置,

    var isMousedown = false;//鼠标左键click和touchstart时判断为真，方便执行mousemove和touchmove
    var mouseX, mouseY, preMouseX, preMouseY;//mouseX,mouseY为画板拖动时鼠标在画板相对位置，pre为上一个位置，用来做相对位移
    var canvasMoveTop;//画板拖动时的top
    var canvasMoveLeft;//画板拖动时的left

    var moveX = 0, moveY = 0;//画板中正在画时鼠标或手指在画板中的相对位置
    var canMoveColorBar = false;//是否可以拖动色板， 色板click和touchend事件出发时为true
    var colorBarMoving = false;//横向和纵向色板是否正在移动，正在移动为true，不可选择颜色，解决拖一下就选颜色的问题
	var doubleFinger = {initLong: 0, isTouched: false};
	var largerCenter = { x: 16, y: 16 };
	var touchStartLength = 0;
	var hasContinueDraw = false;
	var colorBoxWidth = 0;
    window.onload = function (ev) {
        var topMenuNumber = byId('topMenu').getElementsByTagName('div');
        var canvas = byId('canvas');
        var context = canvas.getContext('2d');
        var secondCanvas = byId('secondCanvas');
        var secondContext = secondCanvas.getContext('2d');

        var preBlock = new Block(nowColor, 0, 0, false);//用于绘图过程中move事件触动时判断点击点是否移动到其他小方块位置，同一个小方块的位置算画一次。
        var allBtn = byId('controlBoard').getElementsByTagName('div');//底部按钮div
        byId('save').isChange = false;//画板非空白时为true;
		byId('smallerCanvas').isClick = false;
		byId('largerCanvas').isClick = false;

        initBlockList(false);//初始化全部小方块为背景颜色
        getView();//设置页面布局
        initColor();//初始化横纵色板及相关事件
		getCanvasView();//画布初始化

        for (var i = 0; i < allBtn.length; i++) {
            allBtn[i].isActive = false;//初始化底部按钮点击状态为false
            allBtn[i].unActiveImage = bottomBtnUnactiveImg[i];//初始化底部按钮图片
        }
        allBtn[3].isActive = true;//默认画笔工具激活
        startMove(document.body, {'opacity': 100});//之前设置了body的opacity为0，界面加载完后在这里平滑渐入，可以改用jquery实现

		canvas.onmousedown = canvas.ontouchstart = function (e) {
			mouseX = e.touches !== undefined ? e.touches[0].clientX : e.clientX;
			mouseY = e.touches !== undefined ? e.touches[0].clientY : e.clientY;
            // console.log(mouseX)
			byId('allColors').style.display = 'none';
            var rightDown = e.touches !== undefined ? e.touches.length === 1 : e.button === 0;//手机单指触屏或鼠标左键
            var doubleTouch = e.touches !== undefined ? e.touches : '';
            if (rightDown) {
                setTimeout(function(){
					if(!doubleFinger.isTouched){
                        isMousedown = true;
                        if (allBtn[0].isActive) {//hand按钮激活
                            preMouseX = mouseX;
                            preMouseY = mouseY;
                        }
                        else {//开始绘画
                            byId('save').isChange = true;
                            byId('save').style.opacity = 1;
                            if(largerMultiple !== 6) byId('largerCanvas').style.opacity = 1;
                            if (largerMultiple > 2) byId('smallerCanvas').style.opacity = 1;
                            start(e);
                        }
					}
				},10)

            }
            else if (doubleTouch.length === 2) {
                // console.log(doubleTouch[0].clientX, doubleTouch[1].clientX)
                // console.log(doubleTouch[0].clientY, doubleTouch[1].clientY)
				doubleFinger.isTouched = true;
                var fingerLong = Math.sqrt(Math.pow(doubleTouch[0].clientX - doubleTouch[1].clientX, 2) + Math.pow(doubleTouch[0].clientY - doubleTouch[1].clientY, 2));
				touchStartLength = fingerLong;
                // console.log(fingerLong)
                var mye = {
                    clientX: (doubleTouch[0].clientX + doubleTouch[1].clientX) / 2,
                    clientY: (doubleTouch[0].clientY + doubleTouch[1].clientY) / 2
                }
                // start(mye);
                preMouseX = mouseX;
                preMouseY = mouseY;
            }

		};
		canvas.onmousemove = canvas.ontouchmove = function (e) {
		    var event = event || e;
		    event.preventDefault();
		    var rightMove = e.touches !== undefined ? e.touches.length === 1 : e.button === 0;//手机单指触屏或鼠标左键
			var doubleTouch = e.touches !== undefined ? e.touches : null;
			if (rightMove) {
			    var ev = e.touches !== undefined ? e.touches[0] : e;

				if (allBtn[0].isActive && isMousedown) {//hand按钮激活 && 鼠标左键按下或单指触摸canvas
					canvasMove(ev);
				}
				else if (isMousedown && !allBtn[0].isActive) {
					move(e);//开始绘画move
				}
			}
			else if(doubleTouch.length === 2){
			    // console.log(doubleTouch[0].clientX, doubleTouch[1].clientX)
                // console.log(doubleTouch[0].clientY, doubleTouch[1].clientY)
                var fingerLongChange = Math.sqrt(Math.pow(doubleTouch[0].clientX-doubleTouch[1].clientX, 2)+Math.pow(doubleTouch[0].clientY-doubleTouch[1].clientY, 2));
                //
                // console.log(fingerLong)
                var mye = {
			        clientX : doubleTouch[0].clientX,
                    clientY : doubleTouch[0].clientY
                };
                canvasMove(mye);
                // largerMultiple += (fingerLongChange-touchStartLength)/touchStartLength * 3;
                // touchStartLength = fingerLongChange;
				// if(largerMultiple > 6){
				//     largerMultiple = 6;
				// }else if(largerMultiple < 2){
				//     largerMultiple = 2;
				// }else{
                 //    scrollChangeCanvas(largerMultiple)
				// }

			}
		};
		canvas.onmouseup = canvas.ontouchend = function (e) {
                isMousedown = false;
                doubleFinger.isTouched = false;
                // console.log(largerCenter)
                if (!allBtn[0].isActive) {

                    //控制最大步数
                    if(nowStatus > historyCount){
                        nowStatus = historyCount;
                        allStatus = nowStatus;

                        for (var i=0;i<nowStatus;i++){
                            history[i] = history[i+1];
                        }
                    }

                    history[nowStatus] = [];
                    for (var i = 0; i < 32; i++) {
                        history[nowStatus][i] = [];
                        for (var j = 0; j < 32; j++) {
                            history[nowStatus][i][j] = new Block(blockList[i][j].color, blockList[i][j].x, blockList[i][j].y, blockList[i][j].isBackgroundColor);
                        }
                    }//记录绘画历史
					drawEachBlock(blockList, secondContext, normalWidth);
                    getPreView();//小图预览画板图像
                }
            };

		if(detectmob()){
            byId('mHead').ontouchstart = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('topMenu').ontouchstart = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('head').ontouchstart = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('main').ontouchstart = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('pre').ontouchstart = function () {
                historyBtnClick(this, -1);
            };
            byId('next').ontouchstart =  function () {
                historyBtnClick(this, 1);
            };
            byId('back').ontouchstart = function () {
                window.location.href = 'draw_monster1.html?timeStemp='+new Date().getTime();
            };
            byId('clear').ontouchstart = function () {
                press(this.getElementsByTagName('img')[0], 'clear', function () {
                    clear(this)
                }.bind(this));
            };
            byId('save').ontouchstart = function () {
                press(this.getElementsByTagName('img')[0], 'save', function () {
                    save(this);
                }.bind(this));
            };
            byId('upload').ontouchstart = function () {
                press(this.getElementsByTagName('img')[0], 'upload', function(){
                    // console.log(this)
                }.bind(this));
            };
            byId('share').ontouchstart = function () {
                press(this.getElementsByTagName('img')[0], 'share', function () {
                    toshareImg();
                }.bind(this));
            };
            byId('largerCanvas').ontouchstart = function () {
                largerCanvas(this);
            };
            byId('smallerCanvas').ontouchstart = function () {
                smallerCanvas(this);
            };
            byId('handMove').ontouchstart = function () {
                allBtn[0].isActive = true;//激活hand
                this.src = '../static/images/hand-active.gif';
                for (var i = 0; i < allBtn.length; i++) {
                    if (i !== 0 && i !== 1) {
                        allBtn[i].isActive = false;
                        if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                            allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                    }
                }//其他底部按钮关闭
            };
            byId('bgc').ontouchstart = function () { //点击切换背景颜色
                nowBgc++;
                nowBgc = nowBgc > 2 ? 0 : nowBgc;
                var _this = this;
                var timeNumber = 0;

                _this.src = backgroundGroup[nowBgc].bg_active_image;
                var timer = setInterval(function () {
                    if (timeNumber > 10) {
                        //_this.src = backgroundGroup[nowBcg].bg_image;
                        clearInterval(timer);
                        backgroundColor = backgroundGroup[nowBgc].bg_color;
                        _this.src = backgroundGroup[nowBgc].bg_image;
                        if (allBtn[4].isActive) {//如果橡皮激活，橡皮等于背景颜色，橡皮绘图时会改变小方块的isBackgroundColor为true
                            nowColor = backgroundColor;
                        }
                        for (var i = 0; i < 32; i++) {
                            for (var j = 0; j < 32; j++) {
                                if (blockList[i][j].isBackgroundColor) {
                                    blockList[i][j].color = backgroundColor;
                                }
                            }
                        }//改变当前绘图信息数组的背景颜色信息
                        for (var i = 0; i <= allStatus; i++) {
                            for (var j = 0; j < 32; j++) {
                                for (var k = 0; k < 32; k++) {
                                    try {
                                        if (history[i][j][k].isBackgroundColor)
                                            history[i][j][k].color = backgroundColor;
                                    } catch (e) {
                                        console.log(e)
                                    }

                                }
                            }
                        }//改变历史记录中所有状态下的背景颜色信息
                        drawEachBlock(history[nowStatus], context, eachWidth);//绘制当前状态下的图像
                        drawEachBlock(history[nowStatus], secondContext, normalWidth);
                        byId('save').isChange = true;
                        byId('save').style.opacity = 1;
                        getPreView();//形成预览
                        //this.style.backgroundColor = backgroundColor;//按钮背景色变成画板背景色
                    }
                    timeNumber++;
                }, 5);//闪一闪。。

            };
            allBtn[2].ontouchstart = function () {
                if (getStyle(byId('allColors'), 'display') === 'block') {//getStyle在common.js里，可以获取元素样式
                    byId('allColors').style.display = 'none';
                    byId('trangle').style.transform = 'rotateX(0deg)';
                }
                else {
                    byId('allColors').style.display = 'block';
                    byId('trangle').style.transform = 'rotateX(180deg)';
                }
            };
            byId('pencil').ontouchstart = function () {
                allBtn[3].isActive = true;//画笔激活
                allBtn[4].isActive = false;//橡皮关闭
                nowColor = preColor;//当前颜色恢复
                this.src = '../static/images/pen-active.gif';
                for (var i = 0; i < allBtn.length; i++) {
                    if (i !== 3 && i!==1) {
                        allBtn[i].isActive = false;
                        if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                            allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                    }
                }
            };
            byId('eraser').ontouchstart = function () {
                if (!allBtn[4].isActive) {//防止双击橡皮，画笔变为背景色
                    allBtn[4].isActive = true;
                    preColor = nowColor;
                    nowColor = backgroundColor;
                    this.src = '../static/images/eraser-active.gif';
                    for (var i = 0; i < allBtn.length; i++) {
                        if (i !== 4 && i!==1) {
                            allBtn[i].isActive = false;
                            if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                                allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                        }
                    }
                }
            };
		}
		else{
            byId('mHead').onmousedown = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('topMenu').onmousedown = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('head').onmousedown = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('main').onmousedown = function () {
                byId('allColors').style.display = 'none';
                byId('trangle').style.transform = 'rotateX(0deg)';
            };
            byId('pre').onmousedown = function () {
                historyBtnClick(this, -1);
            };
            byId('next').onmousedown = function () {
                historyBtnClick(this, 1);
            };
            byId('back').onmousedown = function () {
                window.location.href = 'draw_monster1.html?timeStemp='+new Date().getTime();
            };
            byId('clear').onmousedown = function () {
                press(this.getElementsByTagName('img')[0], 'clear', function () {
                    clear(this)
                }.bind(this));
            };
            byId('save').onmousedown = function () {
                press(this.getElementsByTagName('img')[0], 'save', function () {
                    save(this);
                }.bind(this));
            };
            byId('upload').onmousedown = function () {
                press(this.getElementsByTagName('img')[0], 'upload', function(){
                     console.log("上传图片");
                }.bind(this));
            };
            byId('share').onmousedown = function () {
                press(this.getElementsByTagName('img')[0], 'share', function () {
                    toshareImg();

                }.bind(this));
            };
            byId('largerCanvas').onmousedown = function () {
                largerCanvas(this);
            };
            byId('smallerCanvas').onmousedown = function () {
                smallerCanvas(this);
            };
            byId('handMove').onmousedown = function () {
                allBtn[0].isActive = true;//激活hand
                this.src = '../static/images/hand-active.gif';
                for (var i = 0; i < allBtn.length; i++) {
                    if (i !== 0 && i !== 1) {
                        allBtn[i].isActive = false;
                        if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                            allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                    }
                }//其他底部按钮关闭
            };
            byId('bgc').onmousedown = function () { //点击切换背景颜色
                nowBgc++;
                nowBgc = nowBgc > 2 ? 0 : nowBgc;
                var _this = this;
                var timeNumber = 0;

                _this.src = backgroundGroup[nowBgc].bg_active_image;
                var timer = setInterval(function () {
                    if (timeNumber > 10) {
                        //_this.src = backgroundGroup[nowBcg].bg_image;
                        clearInterval(timer);
                        backgroundColor = backgroundGroup[nowBgc].bg_color;
                        _this.src = backgroundGroup[nowBgc].bg_image;
                        if (allBtn[4].isActive) {//如果橡皮激活，橡皮等于背景颜色，橡皮绘图时会改变小方块的isBackgroundColor为true
                            nowColor = backgroundColor;
                        }
                        for (var i = 0; i < 32; i++) {
                            for (var j = 0; j < 32; j++) {
                                if (blockList[i][j].isBackgroundColor) {
                                    blockList[i][j].color = backgroundColor;
                                }
                            }
                        }//改变当前绘图信息数组的背景颜色信息
                        for (var i = 0; i <= allStatus; i++) {
                            for (var j = 0; j < 32; j++) {
                                for (var k = 0; k < 32; k++) {
                                    try {
                                        if (history[i][j][k].isBackgroundColor)
                                            history[i][j][k].color = backgroundColor;
                                    } catch (e) {
                                        console.log(e)
                                    }

                                }
                            }
                        }//改变历史记录中所有状态下的背景颜色信息
                        drawEachBlock(history[nowStatus], context, eachWidth);//绘制当前状态下的图像
                        drawEachBlock(history[nowStatus], secondContext, normalWidth);
						byId('save').isChange = true;
						byId('save').style.opacity = 1;
                        getPreView();//形成预览
                        //this.style.backgroundColor = backgroundColor;//按钮背景色变成画板背景色
                    }
                    timeNumber++;
                }, 5);//闪一闪。。



            };
            allBtn[2].onmousedown = function () {
                if (getStyle(byId('allColors'), 'display') === 'block') {//getStyle在common.js里，可以获取元素样式
                    byId('allColors').style.display = 'none';
                    byId('trangle').style.transform = 'rotateX(0deg)';
                }
                else {
                    byId('allColors').style.display = 'block';
                    byId('trangle').style.transform = 'rotateX(180deg)';
                }
            };
            byId('pencil').onmousedown = function () {
                allBtn[3].isActive = true;//画笔激活
                allBtn[4].isActive = false;//橡皮关闭
                nowColor = preColor;//当前颜色恢复
                this.src = '../static/images/pen-active.gif';
                for (var i = 0; i < allBtn.length; i++) {
                    if (i !== 3 && i !== 1) {
                        allBtn[i].isActive = false;
                        if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                            allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                    }
                }
            };
            byId('eraser').onmousedown = function () {
                if (!allBtn[4].isActive) {//防止双击橡皮，画笔变为背景色
                    allBtn[4].isActive = true;
                    preColor = nowColor;
                    nowColor = backgroundColor;
                    this.src = '../static/images/eraser-active.gif';
                    for (var i = 0; i < allBtn.length; i++) {
                        if (i !== 4 && i !== 1) {
                            allBtn[i].isActive = false;
                            if (allBtn[i].getElementsByTagName('img')[0] && i !== 2)
                                allBtn[i].getElementsByTagName('img')[0].src = allBtn[i].unActiveImage;
                        }
                    }
                }
            };
		}

		//去分享图片
		toshareImg = function () {
		    console.log("分享图片");
		    if(byId("save").isChange){
                localStorage.setItem("shareimg",canvas.toDataURL()); //突然感觉没啥卵用 因为火狐大法 又有卵用了
                window.location.href = 'ShareView.html';
			}else{
		        alert("不能分享空图片");
			}
        }

        document.body.addEventListener('mouseup', function (e) {
            isMousedown = false;
            canMoveColorBar = false;
        });
        window.onresize = function () {
            // getView();
            // initColor();
        };//窗口变化时改变页面布局，可不用，不重要
        window.onscroll = function (ev) {
            paddingLeft = canvas.offsetLeft - document.body.scrollLeft + byId('wrap').offsetLeft;
            paddingTop = canvas.offsetTop - document.body.scrollTop + byId('wrap').offsetTop;
        };//不重要，y方向有滚动条时使用，然而没有滚动条

        function getView() {
            clientH = document.documentElement.clientHeight;
            clientW = document.documentElement.clientWidth;
            byId('wrap').style.height = clientH + 'px';
            byId('wrap').style.width = clientW < clientH * 0.75 ? clientW + 'px' : clientH * 0.6 + 'px';
            byId('mHead').style.height = clientH * 0.064 + 'px';
            byId('topMenu').style.height = clientH * 0.07 + 'px';
            for (var i = 0; i < topMenuNumber.length; i++) {
                topMenuNumber[i].style.height = byId('topMenu').offsetHeight * 0.8 + 'px';
                topMenuNumber[i].style.width = byId('topMenu').offsetHeight * 0.8 + 'px';
                topMenuNumber[i].style.margin = byId('topMenu').offsetHeight * 0.08 + 'px ';
            }

            byId('controlBoard').style.height = clientH * 0.1 + 'px';

            if(!detectmob()){
                byId('controlBoard').style.height = clientH * 0.08 + 'px';
			}
            var controlBoardDiv = byId('controlBoard').getElementsByTagName('div');
            for(var i=0;i<controlBoardDiv.length;i++){
                if(i!== 2){
                    // console.log(controlBoardDiv[i].getElementsByTagName('img')[0].offsetHeight)
                    controlBoardDiv[i].getElementsByTagName('img')[0].style.width = controlBoardDiv[i].getElementsByTagName('img')[0].offsetHeight+'px';
                }
            }
            byId('nowColor').style.width = clientH * 0.045 + 'px';
            byId('nowColor').style.height = clientH * 0.045 + 'px';
            byId('c').style.width = clientH * 0.045 + 'px';
            byId('c').style.height = clientH * 0.045 + 'px';
            byId('c').style.borderRadius = clientH * 0.012+'px';
            byId('nowColor').style.marginTop = -clientH * 0.045 + 'px';

        }//页面布局函数
		function getCanvasView() {
            //console.log(byId('wrap').offsetHeight-byId('mHead').offsetHeight-byId('topMenu').offsetHeight-byId('allColor').offsetHeight-byId('controlBoard').offsetHeight)
            byId('head').style.height = clientH * 0.09 + 'px';

            byId('preView').style.height = byId('head').offsetHeight * 0.88 + 'px';
            byId('preView').style.marginTop = byId('head').offsetHeight * 0.05 + 'px';
            byId('pre').style.height = byId('head').offsetHeight * 0.88 + 'px';
            byId('pre').style.width = byId('head').offsetHeight * 0.88 + 'px';
            byId('pre').style.marginTop = byId('head').offsetHeight * 0.05 + 'px';
            byId('next').style.height = byId('head').offsetHeight * 0.88 + 'px';
            byId('next').style.width = byId('head').offsetHeight * 0.88 + 'px';
            byId('next').style.marginTop = byId('head').offsetHeight * 0.05 + 'px';
            byId('largerCanvas').style.height = byId('head').offsetHeight * 0.88 + 'px';
            byId('largerCanvas').style.width = byId('head').offsetHeight * 0.88 + 'px';
            byId('largerCanvas').style.marginTop = byId('head').offsetHeight * 0.05 + 'px';
            byId('smallerCanvas').style.height = byId('head').offsetHeight * 0.88 + 'px';
            byId('smallerCanvas').style.width = byId('head').offsetHeight * 0.88 + 'px';
            byId('smallerCanvas').style.marginTop = byId('head').offsetHeight * 0.05 + 'px';
            preCanvasHeight = byId('wrap').offsetHeight-byId('mHead').offsetHeight-byId('topMenu').offsetHeight-byId('head').offsetHeight-byId('allColor').offsetHeight-byId('controlBoard').offsetHeight
            preCanvasWidth = parseInt(byId('wrap').offsetWidth);//-byId('largerCanvas').offsetLeft-(byId('wrap').offsetWidth-byId('next').offsetLeft-byId('next').offsetWidth));
            var smallerPreWH = preCanvasHeight < preCanvasWidth ? preCanvasHeight : preCanvasWidth;
            // console.log(smallerPreWH, preCanvasWidth, preCanvasHeight);
			if(detectmob()){
                canvasWidth = 0 === smallerPreWH % 32 ? smallerPreWH - 64 : smallerPreWH - smallerPreWH % 32;
			}else{
                canvasWidth = 0 === smallerPreWH % 32 ? smallerPreWH - 64 : smallerPreWH - smallerPreWH % 32 -32;
			}


            byId('canvasBox').style.width = canvasWidth + 'px';
            byId('canvasBox').style.height = canvasWidth + 'px';
            byId('main').style.marginTop = (preCanvasHeight - canvasWidth)/2 + 'px';

            canvas.width = canvasWidth;
            canvas.height = canvasWidth;

            eachWidth = (canvasWidth / 32);
            normalWidth = eachWidth;

            secondCanvas.width = canvasWidth;
            secondCanvas.height = canvasWidth;

            paddingLeft = canvas.offsetLeft - document.body.scrollLeft + byId('wrap').offsetLeft;
            paddingTop = canvas.offsetTop - document.body.scrollTop + byId('wrap').offsetTop;

            byId('largerCanvas').style.marginLeft = getStyle(byId('canvasBox'),'marginLeft');
            byId('pre').style.marginLeft = byId('wrap').offsetWidth - byId('next').offsetLeft-byId('next').offsetWidth-parseInt(getStyle(byId('canvasBox'),'marginLeft'))+'px';
            // alert(byId('canvasBox').offsetTop)
            drawEachBlock(history[nowStatus], context, eachWidth);
            drawEachBlock(history[nowStatus], secondContext, normalWidth);
            getPreView();
        }

        function start(e){

            var event = e.touches !== undefined ? e.touches[0] : e;
            var startX = (event.clientX - paddingLeft) < 0 ? 0 : (event.clientX - paddingLeft) > canvas.width ? canvas.width : (event.clientX - paddingLeft);
            var startY = (event.clientY - paddingTop) < 0 ? 0 : (event.clientY - paddingTop) > canvas.width ? canvas.width : (event.clientY - paddingTop);
            var nowBlockX = parseInt((startX / eachWidth));
            var nowBlockY = parseInt((startY / eachWidth));
            if (nowStatus !== allStatus) {
                for (var i = 0; i < 32; i++) {
                    for (var j = 0; j < 32; j++) {
                        blockList[i][j] = new Block(history[nowStatus][i][j].color, history[nowStatus][i][j].x, history[nowStatus][i][j].y, history[nowStatus][i][j].isBackgroundColor);
                    }
                }
            }
            nowStatus++;
            allStatus = nowStatus;
            blockList[nowBlockX][nowBlockY].color = nowColor;
            blockList[nowBlockX][nowBlockY].isBackgroundColor = allBtn[4].isActive;
            preBlock = new Block(nowColor, nowBlockX, nowBlockY, allBtn[4].isActive);

            drawEachBlock(blockList, context, eachWidth);
        }//绘图时的mousedown和touchstart事件

        function move(e) {
            var event = e.touches !== undefined ? e.touches[0] : e;
            var moveX = (event.clientX - paddingLeft) < 0 ? 0 : (event.clientX - paddingLeft) > canvas.width ? canvas.width : (event.clientX - paddingLeft);
            var moveY = (event.clientY - paddingTop) < 0 ? 0 : (event.clientY - paddingTop) > canvas.width ? canvas.width : (event.clientY - paddingTop);
            var nowBlockX = parseInt(moveX / eachWidth);
            var nowBlockY = parseInt(moveY / eachWidth);
            if (nowBlockX !== preBlock.x || nowBlockY !== preBlock.y) {
                checkBlockIsAccessed(preBlock.x, preBlock.y, nowBlockX, nowBlockY);
                blockList[nowBlockX][nowBlockY].color = nowColor;
                blockList[nowBlockX][nowBlockY].isBackgroundColor = allBtn[4].isActive;
                preBlock.x = nowBlockX;
                preBlock.y = nowBlockY;

                drawEachBlock(blockList, context, eachWidth);
            }
        }//绘图时的mousemove和touchmove事件

		function canvasMove(ev) {
            mouseX = ev.clientX;
            mouseY = ev.clientY;
            canvasMoveTop = ev.clientY - preMouseY + parseInt(getStyle(byId('canvas'), 'marginTop'));
            canvasMoveLeft = ev.clientX - preMouseX + parseInt(getStyle(byId('canvas'), 'marginLeft'));
            if (canvasMoveTop <= -(eachWidth * 32 - byId('canvasBox').offsetHeight)) {
                canvasMoveTop = -(eachWidth * 32 - byId('canvasBox').offsetHeight);
            }
            else if (canvasMoveTop >= 0) {
                canvasMoveTop = 0;
            }
            if (canvasMoveLeft <= -(eachWidth * 32 - byId('canvasBox').offsetHeight)) {
                canvasMoveLeft = -(eachWidth * 32 - byId('canvasBox').offsetHeight);
            }
            else if (canvasMoveLeft >= 0) {
                canvasMoveLeft = 0;
            }
            canvas.style.marginTop = canvasMoveTop + 'px ';
            canvas.style.marginLeft = canvasMoveLeft + 'px ';
            //console.log('偏移量top: '+ Math.round(canvasMoveTop/eachWidth) + ' 偏移量left: ' + Math.round(canvasMoveLeft/eachWidth));
            largerCenter.x = Math.round((normalWidth*16+canvasMoveLeft)/eachWidth);
            largerCenter.y = Math.round((normalWidth*16+canvasMoveTop)/eachWidth);
            preMouseX = mouseX;
            preMouseY = mouseY;
            paddingLeft = canvas.offsetLeft - document.body.scrollLeft + byId('wrap').offsetLeft;
            paddingTop = canvas.offsetTop - document.body.scrollTop + byId('wrap').offsetTop;
        }

        function scrollChangeCanvas(magnification) {
            if (history[nowStatus] !== defaultCanvas || hasContinueDraw) {
                if (eachWidth < normalWidth) {
                    eachWidth = normalWidth;
                    canvas.width = eachWidth * 32;
                    canvas.height = eachWidth * 32;
                    canvas.style.margin = '0';
                    drawEachBlock(history[nowStatus], context, eachWidth);
                }
                else {
                    eachWidth = Math.round(magnification * normalWidth / 2);
                    var nextEachWidth = Math.round((magnification+1) * normalWidth / 2);
                    canvas.width = eachWidth * 32;
                    canvas.height = eachWidth * 32;
					var pianyiliang = {x:largerCenter.x, y: largerCenter.y};
                    canvasMoveTop = -(eachWidth-normalWidth) * 16; // + pianyiliang.y*eachWidth;
                    canvasMoveLeft = -(eachWidth-normalWidth) * 16; // + pianyiliang.x*eachWidth;
					// console.log(largerCenter)
                    // console.log('largerMultiple: '+ largerMultiple + ' magnification: ' + magnification);
                    // console.log('canvasMoveTop: ' + canvasMoveTop + ' canvasMoveLeft: ' + canvasMoveLeft );
                    // console.log('eachWidth: ' + eachWidth + ' normalWidth: ' + normalWidth+ ', '+ parseInt(getStyle(byId('canvas'), 'marginTop')));
                    if (canvasMoveTop <= -(eachWidth * 32 - byId('canvasBox').offsetHeight)) {
                        canvasMoveTop = -(eachWidth * 32 - byId('canvasBox').offsetHeight);
                    }
                    else if (canvasMoveTop >= 0) {
                        canvasMoveTop = 0;
                    }
                    if (canvasMoveLeft <= -(eachWidth * 32 - byId('canvasBox').offsetHeight)) {
                        canvasMoveLeft = -(eachWidth * 32 - byId('canvasBox').offsetHeight);
                    }
                    else if (canvasMoveLeft >= 0) {
                        canvasMoveLeft = 0;
                    }
                    // console.log(getStyle(canvas,'margin'));
                    canvas.style.marginTop = canvasMoveTop + 'px ';
                    canvas.style.marginLeft = canvasMoveLeft + 'px ';
                    drawEachBlock(history[nowStatus], context, eachWidth);
                }
            }
            // console.log(getStyle(canvas,'margin'));
            paddingLeft = canvas.offsetLeft - document.body.scrollLeft + byId('wrap').offsetLeft;
            paddingTop = canvas.offsetTop - document.body.scrollTop + byId('wrap').offsetTop;
        }//放大缩小函数，名字源自鼠标中键滚动放大缩小。。。

        function getPreView() {
            byId('preView').getElementsByTagName('img')[0].src = secondCanvas.toDataURL();
        }//生成预览

        function drawWhiteBord(context) {
            context.fillStyle = "rgba(255,255,255,1)";
            context.fillRect(0, 0, canvas.width, canvas.height);
        }//清空画板，画板宽高变为32的倍数后，貌似不需要了，但是放着不会出错

        function initBlockList(isClear) {
            var isClears = isClear;
            //判断id
            if(allmonster != null && !isClears){
                var id = monsterId;
                if(getQueryString("create") != null){
                    for (var i = 0; i < 32; i++) {
                        blockList[i] = [];
                        for (var j = 0; j < 32; j++) {
                            blockList[i][j] = new Block(backgroundColor, i, j, true);
                        }
                    }
				}
				else{
                    hasContinueDraw = true;
                    byId('largerCanvas').style.opacity = 1;
                    byId('largerCanvas').isClick = false;

                    var continueDraw = allmonster[id].cvinfo;
                    for (var i = 0; i < 32; i++) {
                        blockList[i] = [];
                        for (var j = 0; j < 32; j++) {
                            blockList[i][j] = new Block(continueDraw[i][j].color, i, j, continueDraw[i][j].isBackgroundColor);
                        }
                    }
				}

            }else{
                for (var i = 0; i < 32; i++) {
                    blockList[i] = [];
                    for (var j = 0; j < 32; j++) {
                        blockList[i][j] = new Block(backgroundColor, i, j, true);
                    }
                }
			}

            nowStatus = 0;
            allStatus = nowStatus;
            history[nowStatus] = [];
            for (var i = 0; i < 32; i++) {
                history[nowStatus][i] = [];
                for (var j = 0; j < 32; j++) {
                    history[nowStatus][i][j] = new Block(blockList[i][j].color, blockList[i][j].x, blockList[i][j].y, blockList[i][j].isBackgroundColor);
                }
            }
            defaultCanvas = history[nowStatus];

        }//初始化当前画板绘图信息数组，并设置第0个历史记录

        function drawEachBlock(List, context, eachWidth) {
            //drawWhiteBord(context);
            var i, j;
            for (i = 0; i < 32; i++) {
                for (j = 0; j < 32; j++) {
                    context.fillStyle = List[i][j].color;
                    context.fillRect(List[i][j].x * eachWidth, List[i][j].y * eachWidth, eachWidth, eachWidth);
                }
            }
            if(context.canvas.id === 'canvas'){
                // console.log('ok')
				drawGrid(List, context);
			}
            if (nowStatus === 0) {
                byId('pre').getElementsByTagName('img')[0].src = '../static/images/unback.gif';
            }
            else {
                byId('pre').getElementsByTagName('img')[0].src = '../static/images/back.gif';
            }
            if (nowStatus === allStatus) {
                byId('next').getElementsByTagName('img')[0].src = '../static/images/unback.gif';
            }
            else {
                byId('next').getElementsByTagName('img')[0].src = '../static/images/back.gif';
            }
        }//绘制传入的绘制信息数组
		
		function drawGrid(List, context) {
			context.strokeStyle = '#eee';
			context.lineWidth = 0.3;
            var i, j;
            for (i = 0; i < 32; i++) {
                for (j = 0; j < 32; j++) {
                    context.beginPath();
                    context.moveTo(List[i][j].x * eachWidth, List[i][j].y * eachWidth);
                    context.lineTo(List[i][j].x * eachWidth+eachWidth, List[i][j].y * eachWidth);
                    context.lineTo(List[i][j].x * eachWidth+eachWidth, List[i][j].y * eachWidth+eachWidth);
                    context.lineTo(List[i][j].x * eachWidth, List[i][j].y * eachWidth+eachWidth);
                    // context.moveTo(List[i][j].x * eachWidth, List[i][j].y * eachWidth+eachWidth);
                    context.lineTo(List[i][j].x * eachWidth, List[i][j].y * eachWidth);
                    context.closePath();

                    context.stroke();
                }
            }
        }

        function Block(color, x, y, isBackgroundColor) {
            this.color = color;
            this.x = x;
            this.y = y;
            this.isBackgroundColor = isBackgroundColor;
            this.isAccessed = function (x1, y1, x2, y2) {
                if (x1 !== x2 && y1 !== y2) {
                    var leftFxY = (this.x - x2) * (y1 - y2) / (x1 - x2) + y2;
                    var rightFxY = (this.x + 1 - x2) * (y1 - y2) / (x1 - x2) + y2;
                    var topFxX = (this.y - y2) * (x1 - x2) / (y1 - y2) + x2;
                    var bottomFxX = (this.y + 1 - y2) * (x1 - x2) / (y1 - y2) + x2;
                    if (leftFxY > this.y && leftFxY < this.y + 1 || rightFxY > this.y && rightFxY < this.y + 1 || topFxX > this.x && topFxX < this.x + 1 || bottomFxX > this.x && bottomFxX < this.x + 1) {
                        return true;
                    }
                }
                else if (x1 === x2) {
                    if (x1 >= this.x && x1 <= this.x + 1) return true;
                }
                else if (y1 === y2) {
                    if (y1 >= this.y && y1 <= this.y + 1) return true;
                }
                return false;
            }
        }//小方块对象，有一个isAccessed方法，判断小方块是否在两个move点之间，是返回true

        function checkBlockIsAccessed(areaX1, areaY1, areaX2, areaY2) {
            var minX, maxX, minY, maxY;
            minX = areaX1 > areaX2 ? areaX2 : areaX1;
            maxX = areaX1 > areaX2 ? areaX1 : areaX2;
            minY = areaY1 > areaY2 ? areaY2 : areaY1;
            maxY = areaY1 > areaY2 ? areaY1 : areaY2;

            for (var i = minX; i <= maxX; i++) {
                for (var j = minY; j <= maxY; j++) {
                    if (blockList[i][j].isAccessed(areaX1, areaY1, areaX2, areaY2)) {
                        blockList[i][j].color = nowColor;
                        blockList[i][j].isBackgroundColor = allBtn[4].isActive;//根据橡皮开启状态恢复小方块为背景色（擦除）
                    }
                    else {
                        //blockList[i][j].color = "#00ff00";
                    }
                }
            }

        }//检查全部小方块中是否有在两个move点之间的，有就上色

        function initColor() {
            var allColors = document.createElement('div');//创建纵向色板
            allColors.id = "allColors";
            allColors.style.display = 'none';
            allColors.style.height = clientH / 3 + 'px';


            var colorSpan = '', allColorSpan = '';
            allColorSpan += '<div id="allColorBox"><div id="floatColorBox"><div class="active floatColor"></div>';
            colorSpan += '<div id="colorBox"><div class="active eachColor"></div>';
            for (var i = 1; i < allColorName.length; i++) {
                colorSpan += '<div class="eachColor"></div>';//横向色板颜色赋值
                allColorSpan += '<div class="floatColor"></div>';//纵向色板颜色赋值
            }
            allColors.innerHTML = allColorSpan + '</div></div>';
            byId('wrap').appendChild(allColors);//纵向色板加入wrap，成为子节点

            var floatColorBox = byId('floatColorBox');
            var allFloatColors = floatColorBox.getElementsByTagName('div');//获取纵向色板的所有颜色

            byId('allColor').innerHTML = colorSpan + '</div>';

            var colorBox = document.getElementById('colorBox');

            //根据颜色数量设置colorBox宽度
            // console.log(colorBoxWidth)
            byId('allColor').style.bottom = byId('controlBoard').offsetHeight+'px';
            byId('allColor').style.height = clientH * 0.075 + 'px';
            allColors.style.bottom = byId('controlBoard').offsetHeight+byId('allColor').offsetHeight*0.15 + 'px';
            colorBoxWidth = (8 * (allColorName.length + 2) + allColorName.length * (byId('allColor').offsetHeight * 0.7));
            colorBox.style.width = colorBoxWidth+'px';
            var colors = colorBox.getElementsByTagName('div');//获取横向色板的所有颜色
            for (var i = 0; i < colors.length; i++) {//设置每个颜色的宽高和点击事件
                colors[i].style.background = allColorName[i];
                colors[i].style.width = byId('allColor').offsetHeight * 0.7 + 'px';
                colors[i].style.height = byId('allColor').offsetHeight * 0.7 + 'px';
                allFloatColors[i].style.background = allColorName[i];
                allFloatColors[i].style.width = byId('wrap').offsetWidth / 10.5 + 'px';
                allFloatColors[i].style.height = byId('wrap').offsetWidth / 10.5 + 'px';
                colors[i].style.left = 8 * (i + 2) + (byId('allColor').offsetHeight * 0.7) * i + 'px';
                colors[i].style.top = byId('allColor').offsetHeight * 0.1 + 'px';
                if(colors[i].className === "active eachColor"){
                    colors[i].style.width = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                    colors[i].style.height = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                    allFloatColors[i].style.width = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
                    allFloatColors[i].style.height = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
				}
                colors[i].onclick = colors[i].ontouchend = function (i) {
                    return function (e) {
                        var event = event || e;
                        event.preventDefault();
                        if (!colorBarMoving) {
                            nowColor = allColorName[i];
                            preColor = nowColor;
                            byId('eraser').src = '../static/images/eraser.gif';
                            if (!allBtn[0].isActive) byId('pencil').src = '../static/images/pen-active.gif';
                            allBtn[3].isActive = true;
                            allBtn[4].isActive = false;
                            byId('c').style.backgroundColor = nowColor;
                            colors[i].className = "active eachColor";
                            colors[i].style.width = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                            colors[i].style.height = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                            allFloatColors[i].className = "active floatColor";
                            allFloatColors[i].style.width = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
                            allFloatColors[i].style.height = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
                            for (var j = 0; j < allColorName.length; j++) {
                                if (j !== i) {
                                    colors[j].className = "eachColor";
                                    colors[j].style.width = byId('allColor').offsetHeight * 0.7 + 'px';
                                    colors[j].style.height = byId('allColor').offsetHeight * 0.7 + 'px';
                                    allFloatColors[j].className = "floatColor";
                                    allFloatColors[j].style.width = byId('wrap').offsetWidth / 10.5 + 'px';
                                    allFloatColors[j].style.height = byId('wrap').offsetWidth / 10.5 + 'px';
                                }
                            }
                        }

                    }
                }(i);

                allFloatColors[i].onclick= allFloatColors[i].ontouchend = function (i) {
                    return function (e) {
                        var event = event || e;
                        event.preventDefault();
                        if (!colorBarMoving) {
                            nowColor = allColorName[i];
                            preColor = nowColor;
                            byId('eraser').src = '../static/images/eraser.gif';
                            if (!allBtn[0].isActive) byId('pencil').src = '../static/images/pen-active.gif';
                            allBtn[3].isActive = true;
                            allBtn[4].isActive = false;
                            byId('c').style.backgroundColor = nowColor;
                            //allColors.style.display = 'none';
                            if (colors[i].offsetLeft > colorBoxWidth - byId('wrap').offsetWidth) {
                                byId('colorBox').style.left = -colorBoxWidth + byId('wrap').offsetWidth + 'px';
								console.log(colorBoxWidth, byId('wrap').offsetWidth, colors[i].offsetLeft)
                            }
                            else {
                                byId('colorBox').style.left = -colors[i].offsetLeft + 'px';
                                console.log('colorBoxLeft: '+byId('colorBox').offsetLeft, colorBoxWidth, byId('wrap').offsetWidth, colors[i].offsetLeft)
                            }

                            colors[i].className = "active eachColor";
                            colors[i].style.width = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                            colors[i].style.height = byId('allColor').offsetHeight * 0.7 - 4 + 'px';
                            allFloatColors[i].className = "active floatColor";
                            allFloatColors[i].style.width = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
                            allFloatColors[i].style.height = byId('wrap').offsetWidth / 10.5 - 4 + 'px';
                            for (var j = 0; j < allColorName.length; j++) {
                                if (j !== i) {
                                    colors[j].className = "eachColor";
                                    colors[j].style.width = byId('allColor').offsetHeight * 0.7 + 'px';
                                    colors[j].style.height = byId('allColor').offsetHeight * 0.7 + 'px';
                                    allFloatColors[j].className = "floatColor";
                                    allFloatColors[j].style.width = byId('wrap').offsetWidth / 10.5 + 'px';
                                    allFloatColors[j].style.height = byId('wrap').offsetWidth / 10.5 + 'px';
                                }
                            }
                        }

                    }
                }(i);
            }
			byId('floatColorBox').onmousedown = byId('floatColorBox').ontouchstart = function (ev) {
				var event = event || ev;
				event.preventDefault();
				moveY = ev.touches !== undefined ? ev.touches[0].clientY : ev.clientY;
				canMoveColorBar = true;
				colorBarMoving = false;
				if (parseInt(getStyle(this, 'marginTop')) > 0) {
					this.style.marginTop = 0;
				}
				else if (parseInt((getStyle(this, 'marginTop'))) <= -this.offsetHeight + byId('allColorBox').offsetHeight) {
					this.style.marginTop = -this.offsetHeight + byId('allColorBox').offsetHeight+'px';
				}
			};//纵向色板移动开始
			byId('floatColorBox').onmousemove = byId('floatColorBox').ontouchmove = function (ev) {
				var event = event || ev;
				event.preventDefault();
				colorBarMoving = true;
				var movedY = ev.touches !== undefined ? ev.touches[0].clientY - byId('wrap').offsetTop : ev.clientY - byId('wrap').offsetTop;
				var v = movedY - moveY;
				if (canMoveColorBar) {
					if (parseInt(getStyle(this, 'marginTop')) + v >= 0) {
						this.style.marginTop = 0;
					}
					else if (parseInt(getStyle(this, 'marginTop')) + v <= -this.offsetHeight + byId('allColorBox').offsetHeight) {
						this.style.marginTop = -this.offsetHeight + byId('allColorBox').offsetHeight + 'px';
					}
					else {
						this.style.marginTop = parseInt(getStyle(this, 'marginTop')) + v + 'px';
					}
				}
				moveY = movedY;
			};//纵向色板移动
			byId('floatColorBox').onmouseup = byId('floatColorBox').ontouchend = function (ev) {
				canMoveColorBar = false;
			};//纵向色板移动结束
			byId('colorBox').onmousedown = byId('colorBox').ontouchstart = function (ev) {
				canMoveColorBar = true;
				colorBarMoving = false;
				moveX = ev.touches !== undefined ? ev.touches[0].clientX : ev.clientX;
				if (this.offsetLeft > 0) {
					this.style.left = 0;
				}
				else if (this.offsetLeft < -(8 * (allColorName.length + 2) + allColorName.length * (byId('allColor').offsetHeight * 0.7)) - byId('allColor').offsetWidth) {
					this.style.left = -(8 * (allColorName.length + 2) + allColorName.length * (byId('allColor').offsetHeight * 0.7)) - byId('allColor').offsetWidth + 'px';
				}
			};//横向色板移动开始
			byId('colorBox').onmousemove = byId('colorBox').ontouchmove = function (ev) {
				var event = event || ev;
				//event.preventDefault();
				colorBarMoving = true;
				var movedX = ev.touches !== undefined ? ev.touches[0].clientX : ev.clientX;
				var v = movedX - moveX;
				if (canMoveColorBar) {
					if (this.offsetLeft + v >= 0) {
						this.style.left = 0;
					}
					else if (this.offsetLeft + v <= -(8 * (allColorName.length + 2) + allColorName.length * (byId('allColor').offsetHeight * 0.7)) + byId('allColor').offsetWidth) {
						this.style.left = -(8 * (allColorName.length + 2) + allColorName.length * (byId('allColor').offsetHeight * 0.7)) + byId('allColor').offsetWidth + 'px';
					}
					else {
						this.style.left = this.offsetLeft + v + 'px';
					}
				}
				moveX = movedX;
			};//横向色板移动
			byId('colorBox').onmouseup = byId('colorBox').ontouchend = function (ev) {
				canMoveColorBar = false;
			};//横向色板移动结束
        }//初始化色板和各种事件

        function historyGo(to) {
            if (to === 1) {//正向
                if (nowStatus < allStatus) {
                    nowStatus++;
                    byId('save').style.opacity = 1;
                    if(largerMultiple !== 6) byId('largerCanvas').style.opacity = 1;
                    if(largerMultiple !== 2) byId('smallerCanvas').style.opacity = 1;
                    byId('save').isChange = true;
                    drawEachBlock(history[nowStatus], context, eachWidth);
                    drawEachBlock(history[nowStatus], secondContext, normalWidth);
                }
            }
            else if (to === -1) {//反向
                if (nowStatus > 0) {
                    nowStatus--;
                    // console.log(nowStatus)
                    if (history[nowStatus] === defaultCanvas) {
                        byId('save').style.opacity = 0.5;
                        byId('save').isChange = false;
                        if(!hasContinueDraw){
                            byId('largerCanvas').style.opacity = 0.5;
                            byId('smallerCanvas').style.opacity = 0.5;
						}


                    }
                    drawEachBlock(history[nowStatus], context, eachWidth);
                    drawEachBlock(history[nowStatus], secondContext, normalWidth);
                }
            }
            else {
                console.log("error to");
            }
            getPreView();
        }//控制绘图历史

		function historyBtnClick(obj,to) {
            if (obj.getElementsByTagName('img')[0].src.split('images/')[1] === 'back.gif') {
                var _this = obj.getElementsByTagName('img')[0];
                var timeNumber = 0;
                _this.src = '../static/images/back-press.gif';
                var timer = setInterval(function () {
                    if (timeNumber > 5) {
                        _this.src = '../static/images/back.gif';
                        clearInterval(timer);
                        historyGo(to);//后退函数，其他为点击效果，next也一样
                    }
                    timeNumber++;
                }, 10);
            }
        }

        function clear(obj){
            var _this = obj;
            if (confirm('确定清除？')) {
                initBlockList(true);//初始化所有小方块信息，nowStatus等于0
                drawEachBlock(history[nowStatus], context, eachWidth);//绘制画板
                drawEachBlock(history[nowStatus], secondContext, normalWidth);
                canvas.style.margin = 0;//画板位移归零
                getView();//设置页面布局
				getCanvasView();
                byId('pre').style.marginLeft = byId('wrap').offsetWidth - byId('next').offsetLeft-byId('next').offsetWidth-parseInt(getStyle(byId('canvasBox'),'marginLeft'))+'px';
                getPreView();//预览
                byId('save').style.opacity = 0.5;
                byId('largerCanvas').style.opacity = 0.5;
                byId('smallerCanvas').style.opacity = 0.5;
                largerMultiple = 2;//放大倍数归位
                largerCenter = {x:16,y:16};
                byId('save').isChange = false;//不可保存
            }
		}

		function save(obj) {
            if (obj.isChange) {
                // console.log(history[nowStatus])
                // console.log(JSON.stringify(history[nowStatus]));
                if (confirm("是否保存？")) {
                    if (localStorage.getItem('monsters')) {//使用localStorage本地保存数据
                        var allMonsters = JSON.parse(localStorage.getItem('monsters'));
						if(getQueryString('create') == null){
                            var id = monsterId;
                            var onemonster = allMonsters[id];
                            onemonster.image = secondCanvas.toDataURL();
                            onemonster.cvinfo = history[nowStatus];
                            allMonsters[id] = onemonster;

						}else{
						    var onemonster = {
						        "image":secondCanvas.toDataURL(),
								"cvinfo":history[nowStatus],
								"likenum":0
							}
							allMonsters.push(onemonster);
						}
                        localStorage.setItem('monsters', JSON.stringify(allMonsters));
                    }
                    else {
                        var allMonsters = [];
                        var onemonster = {
                            "image":secondCanvas.toDataURL(),
                            "cvinfo":history[nowStatus],
                            "likenum":0
                        }
                        allMonsters.push(onemonster);
                        localStorage.setItem('monsters', JSON.stringify(allMonsters));
                    }
                    obj.isChange = false;
                    alert('保存成功');
                    window.location.href = 'draw_monster.html?id='+window.location.href.split('id=')[1].split('&')[0]+'&timeStamp=' + new Date().getTime();

                }

            }
        }

        function press(obj, name, fn, interval) {
            var _this = obj;
            var timeNumber = 0;
            var interval = interval || 5;
            _this.src = '../static/images/'+name+'-press.gif';
            var timer = setInterval(function () {
                if (timeNumber > 10) {
                    _this.src = '../static/images/'+name+'.gif';
                    clearInterval(timer);
                    //功能函数在这里。。。
					if(fn){
					    fn();
					}
                }
                timeNumber++;
            }, interval);//闪一闪。。
        }

        function largerCanvas(obj) {
            var that = obj;
            if (largerMultiple >= 6) {
                largerMultiple = 6;
            }
            else {
                if ((history[nowStatus] !== defaultCanvas || hasContinueDraw) && !that.isClick) {//画板不为空时

                    that.isClick = true;
                    if (that.getElementsByTagName('img')[0].src.split('images/')[1] !== 'plus2.gif') {
                        var _this = that.getElementsByTagName('img')[0];
                        var timeNumber = 0;
                        _this.src = '../static/images/plus1.gif';
                        var timer = setInterval(function () {
                            if (timeNumber > 5) {
                                _this.src = '../static/images/plus.gif';
                                clearInterval(timer);
                                largerMultiple+=2;
                                if (largerMultiple >= 6) {
                                    that.style.opacity = 0.5;
                                }
                                that.isClick = false;
								//console.log(largerMultiple)
                                scrollChangeCanvas(largerMultiple);//放大画板，通过参数
                                byId('smallerCanvas').style.opacity = 1;
                            }
                            timeNumber++;
                        }, 10);
                    }
                }
                else{
                    console.log((history[nowStatus] !== defaultCanvas || hasContinueDraw) && !that.isClick)
				}
            }
        }

        function smallerCanvas(obj) {
            var that = obj;
            if (largerMultiple <= 2) {
                largerMultiple = 2;
            }
            else {
                if(history[nowStatus] !== defaultCanvas || hasContinueDraw && !that.isClick){//画板不为空时
                    that.isClick = true;
                    if (that.getElementsByTagName('img')[0].src.split('images/')[1] !== 'dev2.gif') {
                        var _this = that.getElementsByTagName('img')[0];
                        var timeNumber = 0;
                        _this.src = '../static/images/dev1.gif';
                        var timer = setInterval(function () {
                            if (timeNumber > 5) {
                                _this.src = '../static/images/dev.gif';
                                clearInterval(timer);
                                largerMultiple-=2;
                                if (largerMultiple <= 2) {
                                    that.style.opacity = 0.5;
                                }
                                that.isClick = false;
                                scrollChangeCanvas(largerMultiple);//缩小画板
                                byId('largerCanvas').style.opacity = 1;
                            }
                            timeNumber++;
                        }, 10);
                    }
                }
            }
        }
    };



    // var vConsole = new VConsole();//移动端console.log使用

</script>


</html>